package com.hrpc.discovery;

import com.hrpc.Constant;
import com.hrpc.discovery.Register;
import com.hrpc.discovery.impl.NacosRegister;
import com.hrpc.discovery.impl.ZookeeperRegister;
import com.hrpc.exceptions.DiscoveryException;

public class RegisterConfig {
    //定义连接的 url zookeeper://127.0.0.1:2181  redis://192.168.12.125:6379
    private final String connectString;

    public RegisterConfig(String connectString) {
        this.connectString = connectString;
    }

    /**
     * 可以使用简单工厂来完成
     * @return
     */
    public Register getRegister() {
        //1.获取注册中心的类型
        String registerType = getRegisterType(connectString,true).toLowerCase().trim();
        if(registerType.equals("zookeeper")){
            String host = getRegisterType(connectString, false);
            return new ZookeeperRegister(host, Constant.TIMEOUT);
        }else if(registerType.equals("nacos")){
            String host = getRegisterType(connectString, false);
            return new NacosRegister();
        }
        throw new DiscoveryException("未发现合适的注册中心");
    }
    private String getRegisterType(String connectString,Boolean isType){
        String[] split = connectString.split("://");
        if (split.length != 2){
            throw new RuntimeException("注册中心不合法！！！");
        }if(isType == true){
            return split[0];
        }else {
            return split[1];
        }
    }
}
